package com.jumi.microservice.order.factory;

import com.jumi.microservice.common.base.dto.BaseRequest;
import com.jumi.microservice.order.context.AbstractTransHandlerContext;
import com.jumi.microservice.order.context.TransHandlerContext;
import com.jumi.microservice.order.convert.TransConvert;
import com.jumi.microservice.order.pipeline.DefaultTransPipeline;
import com.jumi.microservice.order.pipeline.TransOutboundInvoker;
import com.jumi.microservice.order.pipeline.TransPipeline;


/**
 * @author Dirk
 * @Date 2020-08-04 17:31
 */
public abstract class AbstractTransPipelineFactory<T extends BaseRequest> implements TransPipelineFactory<T> {

    @Override
    public TransOutboundInvoker build(T req) {
        //创建转换器
        TransConvert convert = createConvert();
        //转换为上下文
        TransHandlerContext ctx = convert.convertRequest2Ctx(req);
        //向上转型，并且给ctx设置convert，方便后续根据上下文获取返回值
        AbstractTransHandlerContext absContext = (AbstractTransHandlerContext) ctx;
        absContext.setConvert(convert);
        //创建管道
        TransPipeline pipeline = createPipeline(ctx);
        //构建请求处理管道
        doBuild(pipeline);

        return pipeline;
    }

    /**
     * 请求处理
     *
     * @param pipeline
     */
    protected abstract void doBuild(TransPipeline pipeline);

    protected TransPipeline createPipeline(TransHandlerContext ctx) {
        //暂时使用默认实现
        return new DefaultTransPipeline(ctx);
    }

    /**
     * 创建上下文
     *
     * @return
     */
    protected abstract TransHandlerContext createContext();

    /**
     * 上下文转换器
     *
     * @return
     */
    protected abstract TransConvert createConvert();
}
